#include "uart.h"
#include "uart_api.h"
//#include "pdc.h"

uint8_t UART_init(uint32_t baud_rate,uint32_t parity_type,uint32_t channel_mode,uint32_t sys_clk)
{
    uint32_t cd = 0;
    //config io pins for uart
    UART_PORT->PIO_IDR |= (1U<<UART_RX_PIN_NUM)|(1U<<UART_TX_PIN_NUM);
    UART_PORT->PIO_ABSR &= ~((1U<<UART_RX_PIN_NUM)|(1U<<UART_TX_PIN_NUM));
    UART_PORT->PIO_PDR |= (1U<<UART_RX_PIN_NUM)|(1U<<UART_TX_PIN_NUM);
    //UART_PORT->PIO_PUER |= 1U<<UART_TX_PIN_NUM;
    UART_PORT->PIO_PUDR |= 1U<<UART_TX_PIN_NUM;
    UART_PORT->PIO_PUDR |= 1U<<UART_RX_PIN_NUM;
    
    //enable uart clock
    PMC->PMC_PCER0 |= 1U<<ID_UART;
    //reset and disable uart
    UART->UART_CR  |= (UART_CR_RSTRX | UART_CR_RSTTX | UART_CR_RSTSTA\
         | UART_CR_RXDIS | UART_CR_TXDIS);
    //config baud rate
    cd = (sys_clk/baud_rate)/UART_CLK_DIV;
    if (cd < UART_CLK_DIV_MIN_FACTOR || cd > UART_CLK_DIV_MAX_FACTOR)
            return(0);
    UART->UART_BRGR = cd;
    //config uart mode
    UART->UART_MR &= ~((3U<<14)|(7U<<9));
    UART->UART_MR |= ((parity_type<<9)|(channel_mode<<14));
    //disable pdc
	UART->UART_PTCR |= (UART_PTCR_RXTDIS | UART_PTCR_TXTDIS);
	//Enable receiver and transmitter
	UART->UART_CR |= (UART_CR_RXEN | UART_CR_TXEN);
    
    NVIC_SetPriority(UART_IRQn,7);
    NVIC_EnableIRQ(UART_IRQn);
//    uart_disable_tx(UART);
//    pdc_enable_transfer(PDC_UART, PERIPH_PTCR_TXTEN);  
    uart_enable_interrupt(UART, US_IER_RXRDY); 
    return(1);
}

void UART_send_byte(uint8_t *send_buf,uint32_t count)
{
        for(;count>0;count--)
        {
                while((UART->UART_SR & UART_SR_TXEMPTY) == 0);
                UART->UART_THR = *(send_buf++);
        }      
}

void UART_send_string(uint8_t *string)
{
        for(;*string != '\0';string++)
        {
                UART_send_byte(string,1);
        }
}

uint8_t UART_receive_byte(void)
{
        while((UART->UART_SR & UART_SR_RXRDY) == 0);
        return(UART->UART_RHR);
}



